﻿using Modbus.Device;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ClassStyle
{
    internal class ModbusHelper
    {
        private static ModbusHelper _modbusHelper;
        public static ModbusHelper Instance//单例，在整个应用程序中只有一个实例，并且可以通过 ModbusHelper.Instance 全局访问这个实例。
        {
            get
            {
                if (_modbusHelper == null)
                {
                    _modbusHelper = new ModbusHelper();
                }
                return _modbusHelper;
            }
        }
        public ModbusHelper()
        {
            IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });
            //单独线程  去执行，反复需要这个mim这个链接   
            TcpClient tcp = new TcpClient();

            tcp.Connect(ip.ToString(), 502);

            mim = ModbusIpMaster.CreateIp(tcp);
        }

        public ModbusHelper(string name) { }

        public ModbusIpMaster mim;

        public bool Get_modbus_data(string address, string path)
        {
            //设置 虚拟plc为第一个下拉框   Coil Status(0x)
            bool[] arr = mim.ReadCoils(1, 0, 10);
            int index = int.Parse(FileHelper2025.Get_ini_data("PLC信息", address, path + "\\plc.ini"));
            return arr[index];
        }
        public void Set_modbus_data(ushort index, bool value)//通过单例实例调用。
        {
            mim.WriteSingleCoil(1, index, value);
        }
    }
}